package com.ctg.itrdc.mainframe.control;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ctg.itrdc.sysmgr.permission.core.CtgUser;
import com.ctg.itrdc.sysmgr.permission.core.IPermissionService;
import com.ctg.itrdc.sysmgr.permission.core.control.CommonResult;
import com.ctg.itrdc.sysmgr.permission.core.utils.PasswordHelper;
import com.ctg.itrdc.sysmgr.permission.core.utils.WebUtils;

@Controller
@RequestMapping("/system_user")
public class SystemUserController {

	@Resource
	private IPermissionService permissionService;

	@Value("${password.algorithmName:md5}")
	private String algorithmName;

	@Value("${password.hashIterations:1}")
	private int hashIterations;

	/**
	 * @api {post} /system_user/update/password 个人更新密码
	 * @apiGroup system_user
	 * @apiName updatePassword
	 * @apiParam {Long} sysUserId 选传 不传为当前用户
	 * @apiParam {String} oldPassword 必传
	 * @apiParam {String} newPassword 必传
	 * @apiVersion 0.0.1
	 */
	@RequestMapping("/update/password")
	@ResponseBody
	public CommonResult updatePassword(@RequestParam(required = false) Long sysUserId, @RequestParam String oldPassword,
			@RequestParam String newPassword) throws Exception {
		checkLoginUser(sysUserId);
		Map<String, Object> user = permissionService.getUserById(sysUserId);
		String encryptPassword = PasswordHelper.encryptPassword(oldPassword, algorithmName, hashIterations);
		if (!StringUtils.equals(encryptPassword, (String) user.get("password"))) {
			throw new IncorrectCredentialsException("密码错误!");
		}
		String npwd = PasswordHelper.encryptPassword(newPassword, algorithmName, hashIterations);
		permissionService.updatePassword(sysUserId, npwd);
		// 退出
		Subject subject = SecurityUtils.getSubject();
		if (subject != null) {
			subject.logout();
		}
		return new CommonResult(HttpStatus.OK.toString(), "修改密码成功");

	}

	private void checkLoginUser(Long sysUserId) {
		if (sysUserId != null) {
			CtgUser ctgUser = WebUtils.getCtgUser();
			Long sysUserIdSelf = ctgUser.getSysUserId();
			if (!sysUserId.equals(sysUserIdSelf)) {
				throw new AuthenticationException("亲，只能改自己东西哟~");
			}
		}
	}

}
